'use strict';
const dayjs = require("dayjs");

module.exports = app => {
  const { STRING, INTEGER, DATE } = app.Sequelize;
  
  const Students = app.model.define(
    'Students',
    {
      id: { type: INTEGER, primaryKey: true, autoIncrement: true },
      school_id: { type: INTEGER, allowNull: false },
      name: { type: STRING(50), allowNull: false },
      gender: { type: INTEGER },
      phone: { type: STRING(20) },
      email: { type: STRING(100) },
      class_name: { type: STRING(100) },
      major: { type: STRING(100) },
      grade: { type: STRING(20) },
      status: { type: INTEGER, defaultValue: 1 },
      create_time: {
        type: DATE,
        get() {
          return dayjs(this.getDataValue('create_time')).format('YYYY-MM-DD HH:mm:ss');
        }
      },
      update_time: {
        type: DATE,
        get() {
          return dayjs(this.getDataValue('update_time')).format('YYYY-MM-DD HH:mm:ss');
        }
      }
    },
    {
      tableName: 'students',
      timestamps: true,
      createdAt: 'create_time',
      updatedAt: 'update_time',
      indexes: [
        {
          unique: true,
          fields: ['school_id', 'student_id']
        }
      ]
    }
  );

  Students.associate = function() {
    app.model.Students.belongsTo(app.model.Schools, { foreignKey: 'school_id', targetKey: 'id', as: 'school' });
    app.model.Students.hasMany(app.model.Reservations, { foreignKey: 'student_id', as: 'reservations' });
    app.model.Students.hasOne(app.model.MiniProgramUsers, { foreignKey: 'student_id', as: 'mini_program_user' });
  };

  return Students;
};
